﻿using Elsa.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cl.Service.ElsaWorkflow.Activity.ClAudit.BookMarks
{
    public class AuditActivityBookMarkProvider : BookmarkProvider<AuditActivityBookMark, AuditActivity>
    {
        public override async ValueTask<IEnumerable<BookmarkResult>> GetBookmarksAsync(BookmarkProviderContext<AuditActivity> context, CancellationToken cancellationToken)
        {
            var userinfo = (await context.ReadActivityPropertyAsync<AuditActivity, ICollection<string>>(x => x.ApproveUsers, cancellationToken))?.ToList() ?? new List<string>();

            var workName = context.ActivityExecutionContext.WorkflowExecutionContext.WorkflowBlueprint.Name ?? "";
            var model = context.ActivityExecutionContext.WorkflowExecutionContext.WorkflowBlueprint.ContextOptions?.ContextType?.FullName;
            var id = context.ActivityExecutionContext.WorkflowExecutionContext.ContextId?.ToString() ?? "";
            var activeName = context.Activity.ActivityBlueprint.Name;
            if (activeName == "")
            {
                activeName = null;
            }
            List<BookmarkResult> rv = new List<BookmarkResult>();
            if (userinfo?.Any() == true)
            {
                rv.AddRange(userinfo.Select(x => Result(new AuditActivityBookMark(x, workName, activeName, id))));
                if (string.IsNullOrEmpty(model) == false)
                {
                    rv.AddRange(userinfo.Select(x => Result(new AuditActivityBookMark(x, model, activeName, id))));
                }
            }

            if (rv.Count > 0)
            {
                return rv;
            }
            return new BookmarkResult[0];
        }

    }
}
